layui.define(['exbase', 'jquery', 'ExForm', 'layer'], function (exports) {
    var $ = layui.$;
    var exbase = layui.exbase;

    function DynamicDetail(data) {
        var _this = this;
        this.elem = data.elem;
        this.title = data.title;
        this.form = data.form;
        this.url = data.url;
        this.method = data.method || "GET";
        this.contentType = data.contentType || "application/x-www-form-urlencoded";
        this.data = data.data;
        this.success = data.success;
        this.area = data.area || "auto";
        this.convert = data.convert;

        this.loadFormData = function () {
            $.ajax({
                async: false,
                url: this.url,
                type: this.method,
                contentType: this.contentType,
                data: this.data,
                dataType: 'json',
                success: function (data) {
                    if (data.errorCode == exbase.AJAX_SUCCESS_CODE) {
                        _this.data = exbase.getJsonAsForm(data.data);
                    } else {
                        layer.msg("无法加载表单数据！<br>" + data.errorMsg, {icon: 2});
                    }
                }
            })
        };

        this.define = function () {
            this.loadFormData();

            var html;
            layui.use('jquery', function () {
                var $ = layui.jquery;
                html = [`<div>`,
                    function () {
                        if (_this.form) {
                            var array = new Array();
                            _this.form.forEach(function (e) {
                                array.push(`<div class='layui-row layui-form-item'>`);
                                array.push(`<div class='layui-col-xs4'>`);
                                array.push(`<label class="layui-form-label">` + e.label +`</label>`)
                                array.push(`</div>`);
                                var value = e.value
                                if (_this.data) {
                                    value = _this.data[e.name]
                                }
                                array.push(`<div class='layui-col-xs8'>`);
                                array.push(`<label class="layui-form-label">` + _this.convert(e.name, value) +`</label>`)
                                array.push(`</div>`);
                                array.push(`</div>`);
                            });
                            return array.join("");
                        }
                    }(),
                    "</div>"].join("");
            });
            return html;
        };

        this.open = function () {
            layer.open({
               title: _this.title,
                type: 1,
                area: _this.area,
                content: _this.define(),
            })
        }
    }

    exports('DynamicDetail', DynamicDetail);
});